/*
 * 通过kobject_create_and_add函数创建kobjec
 */

#include <linux/device.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/sysfs.h>
#include <linux/kernel.h>
#include <linux/stat.h>
#include <linux/slab.h>
#include <linux/string.h>
 
/*kobject变量*/
static struct kobject *mp_kobj;
 
/*
struct attribute {
	const char		*name;
	mode_t			mode;
#ifdef CONFIG_DEBUG_LOCK_ALLOC
	struct lock_class_key	*key;
	struct lock_class_key	skey;
#endif
};
*/
 
/*struct attribute变量*/
static struct attribute m_attr = {
    .name = "name",
    .mode = S_IRWXUGO,
};
 
/*struct attribute数组*/
static struct attribute *m_attrs[] = {
    &m_attr,
    NULL,/*末尾必须为NULL*/
 
};
 
/**********************************************************/
//sysfs_ops
 
/*
struct sysfs_ops {
	ssize_t	(*show)(struct kobject *, struct attribute *,char *);
	ssize_t	(*store)(struct kobject *,struct attribute *,const char *, size_t);
};
*/
 
/*sysfs_ops的show函数实现*/
static ssize_t kobj_attr_show(struct kobject *kobj, struct attribute *attr,
                              char *buf)
{
    ssize_t count = 0;
 
    printk("%s\n", __FUNCTION__);
    count = sprintf(buf, "%s\n", kobject_name(kobj) );
 
    return count;
}
 
/*sysfs_ops的store函数实现*/
static ssize_t kobj_attr_store(struct kobject *kobj, struct attribute *attr,
                               const char *buf, size_t count)
{
    printk("%s\n", __FUNCTION__);
    return 0;
}
 
/*struct sysfs_ops变量 */
static struct sysfs_ops m_sys_ops = {
    .show 	= kobj_attr_show,
    .store 	= kobj_attr_store,
};
 
 
/**********************************************************/
/*模块加载函数*/
static int __init kobj_init(void)
{
    int error = 0;
    /*struct kobject *kobject_create_and_add(const char *name, struct kobject *parent)
    if use kobject_create_and_add, it will auto bind ktype to dynamic_kobj_ktype
    so we can not set ktype member*/
    mp_kobj = kobject_create_and_add("kobj_demo1_1", NULL);
    if (!mp_kobj) {
        goto out;
    }
 
    printk("%s success.\n", __FUNCTION__);
 
    return 0;
 
out:
    printk("%s failed!\n", __FUNCTION__);
    return error;
}
 
/*模块退出函数*/
static void __exit kobj_exit(void)
{
    //删除kobject
    kobject_del(mp_kobj);
    //使引用计数减1并调用kobj_type的release函数
    kobject_put(mp_kobj);
    printk("%s\n", __FUNCTION__);
}
 
 
module_init(kobj_init);
module_exit(kobj_exit);
 
MODULE_AUTHOR("tonny");
MODULE_DESCRIPTION("kobject demo");
MODULE_LICENSE("GPL"); 

/*
 
与kobject_demo1.c不同的是，kobject_demo2.c并没有创建kobj_type变量


 */

